<template>
  <div class="content">
    <!-- <brand brand1="商品管理" brand2="商品列表"></brand> -->
    <el-backtop :visibility-height="100" :bottom="60" />
    <el-card class="bottom10">
      <el-button type="primary" size="mini" plain>全部（{{ total }}）</el-button>
      <!-- <el-button type="success" size="mini" plain>已上架（{{ 0 }}）</el-button>
      <el-button type="danger" size="mini" plain>未上架（{{ 0 }}）</el-button> -->
      <el-collapse v-model="activeNames" style="margin-top:10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span style="font-size:18px;">筛选查询</span>
          </template>
          <el-form ref="form" :model="form" label-width="100px">
            <div class="search-class">
              <el-form-item label="输入搜索：">
                <el-input v-model="form.keyword" placeholder="输入关键词搜索" clearable/>
              </el-form-item>
              <el-form-item label="商品id：">
                <el-input v-model="form.id" placeholder="输入商品id" clearable/>
              </el-form-item>
              <el-form-item label="商品分类">
                <!-- 级联悬着器 -->
                <el-cascader v-model="cartArr" :options="goodCates" :props="allcate" clearable></el-cascader>
              </el-form-item>
              <el-form-item label="商品品牌：">
                <el-select v-model="form.brand" placeholder="请选择" clearable>
                  <el-option v-for="item in ppOption" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="上架状态：">
                <el-select v-model="form.state" placeholder="请选择" clearable>
                  <el-option v-for="item in goodsStateOption" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="">
                <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
              </el-form-item>
            </div>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      <el-row class="flex-hs tabTop">
        <el-col :span="24">
          <div class="flex-hs">
            <el-button type="success" @click="addItem()">添加商品</el-button>
            <el-button type="danger" :disabled="multipleSelection.length === 0" @click="deleteItem(1)">删除</el-button>
            <el-button type="success" :disabled="multipleSelection.length === 0" @click="addjia">上架商品</el-button>
            <el-button type="danger" :disabled="multipleSelection.length === 0" @click="upjia">下架商品</el-button>
            <el-button type="success" :disabled="multipleSelection.length === 0" @click="addactive">参与活动</el-button>
            <el-button type="success" :disabled="multipleSelection.length === 0" @click="activeclose">取消活动</el-button>
            
          </div>
        </el-col>
      </el-row>
      <el-row class="flex-hs">
        <el-table :data="tableData" border style="width: 100%;margin:20px 0" :loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" label="" width="50" />
          <el-table-column prop="id" label="商品id" width="100" :sortable='true'/>
          <el-table-column prop="code" label="商品货号" width="120" />
          <el-table-column prop="name" label="商品名称"  min-width="150" :show-overflow-tooltip="true"/>
          <el-table-column prop="brand_name" label="所属品牌" width="90"/>
          <el-table-column prop="sale_start_time" label="上架时间" width="160" :sortable='true'/>
          <el-table-column prop="sale_end_time" label="下架时间" width="160" >
            <template slot-scope="scope"> 
              {{scope.row.sale_end_time=='0000-00-00 00:00:00'? '长期有效': scope.row.sale_end_time}}
            </template>
          </el-table-column>
          <el-table-column label="价格" width="150" >
            <template slot-scope="scope"> 
              <span style="color:#b45f06" v-if="scope.row.min_price<scope.row.max_price">￥{{ scope.row.min_price }}-￥{{ scope.row.max_price }}</span>
              <span style="color:#b45f06" v-else>￥{{ scope.row.min_price }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="" label="库存" width="100" /> -->
          <el-table-column prop="sale" label="销量" width="80" />
          <el-table-column prop="state" label="状态" width="80" >
            <template slot-scope="scope">
              <el-tag type='primary' v-if="new Date(scope.row.sale_start_time).getTime()<new Date()&&scope.row.sale_end_time=='0000-00-00 00:00:00'">已上架</el-tag>
              <template v-else>
                <el-tag type='primary' v-if="new Date(scope.row.sale_start_time).getTime()<new Date().getTime()&&new Date().getTime()<new Date(scope.row.sale_end_time).getTime()">已上架</el-tag>
                <el-tag type='danger' v-if="new Date(scope.row.sale_end_time).getTime()<new Date().getTime()">已下架</el-tag>
                <el-tag type="info" v-if="new Date(scope.row.sale_start_time).getTime()>new Date().getTime()">未上架</el-tag>
               
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="discount" label="活动" width="60">
            <template slot-scope="scope">
              <el-tag type='danger' v-if="scope.row.discount==0">否</el-tag>
              <el-tag type='primary' v-if="scope.row.discount==1">是</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="img" label="商品图" width="80">
            <template slot-scope="scope">
              <el-image style="width: 50px;height:50px" :lazy="true" :preview-src-list="[$http.staticURL + JSON.parse(scope.row.imgs)[0]]" :src="$http.staticURL + JSON.parse(scope.row.imgs)[0]" fit="fill" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  <i class="el-icon-more-outline" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="whatIclick('look', scope.row)">查看</el-dropdown-item>
                  <el-dropdown-item :command="whatIclick('copy', scope.row)">复制新建</el-dropdown-item>
                  <el-dropdown-item :command="whatIclick('update', scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item :command="whatIclick('delete', scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row class="flex-he">
        <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </el-row>
    </el-card>
    <add-or-upload v-if="openAddOrUpload" ref="addOrUpload" @save="search" />
    <look-info v-if="openLookInfo" ref="lookInfo" />
  </div>
</template>




<script>
import addOrUpload from './addORupload'
import lookInfo from './lookInfo'
import { mapState } from 'vuex'
import { setTimeout } from 'timers';
export default {
  components: {
    addOrUpload,
    lookInfo
  },
  data() {
    return {
      activeNames: ['1'],
      currentPage: 1,
      pageSize: 20,
      total: 100,
      loading:true,
      form: {
        id:'',
        keyword: '',
        brand: '',
        state:0
      },
      cartArr: [],
      goodCates: [],
      allcate: {
        expandTrigger: 'hover',
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      ppOption: [],
      openAddOrUpload: false,
      openLookInfo:false,
      multipleSelection: [],
      tableData: []
    }
  },
  computed: {
    ...mapState(['$state', 'goodsStateOption', 'goodsState']),
    queryData() {
      let obj = this.form
      obj.cate1 = this.cartArr.length > 0 ? this.cartArr[0] : ''
      obj.cate2 = this.cartArr.length > 1 ? this.cartArr[1] : ''
      obj.count = this.pageSize
      obj.page = this.currentPage
      return obj
    }
  },
  mounted() {
    this.search()
  },
  methods: {
    search() {
      this.$http.httpPost('/products/productsList', this.queryData).then(res => {
        if (res.data.code === 0) {
          this.total = res.data.data.total
          this.tableData = res.data.data.data
          this.loading = false
        }
      })
      this.$http.httpPost('/cate/cateList', { count: 999, page: 1 }).then(res => {
        if (res.data.code == 0) {
          let arr = res.data.data.data
          this.goodCates = this.dataDoJson(arr, 0, 1)

        }
      })
      this.$http.httpPost('/brand/brandList', { count: 999, page: 1 }).then(res => {
        if (res.status === 200) {
          this.ppOption = res.data.data.data

        }
      })
      this.openAddOrUpload = false
    },
    addjia(){
      let aa = this.getIds(this.multipleSelection)
      this.$http.httpPost('products/productsUpdate', { ids: aa, state: 1 }).then(res => {
        if (res.status === 200) {
          this.$message.success('上架成功！')
          setTimeout(()=>{this.search()},100)
        }
      })
    },
    upjia(){
      let bb = this.getIds(this.multipleSelection)
      this.$http.httpPost('products/productsUpdate', { ids: bb, state: 3 }).then(res => {
        if (res.status === 200) {
          this.$message.success('下架成功！')
          setTimeout(()=>{this.search()},100)
        }
      })
    },
    addactive(){
      let cc = this.getIds(this.multipleSelection)
      this.$http.httpPost('products/productsUpdate', { ids: cc, discount: 1}).then(res => {
          if (res.status === 200) {
            this.$message.success('参与活动成功！')
            setTimeout(()=>{this.search()},100)
          }
        })
    },
    activeclose(){
      let dd = this.getIds(this.multipleSelection)
      this.$http.httpPost('products/productsUpdate', { ids: dd, discount: '0'}).then(res => {
          if (res.status === 200) {
            this.$message.success('取消活动成功！')
            setTimeout(()=>{this.search()},100)
          }
        })
    },
    getIds(arr){
      let ids = []
      if(arr.length>0){
        arr.forEach(e=>{
          ids.push(e.id)
        })
        return ids.join()
      }else{
        return ''
      }
    },
    // 递归处理数据
    dataDoJson(data, pid, level) {
      const result = []
      let temp = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].pid === pid) {
          const obj = data[i]
          obj.level = level
          temp = this.dataDoJson(data, data[i].id, level + 1)
          if (temp.length > 0) {
            obj.children = temp
          }
          result.push(obj)
        }
      }
      return result
    },
    
    addItem(val) {
      console.log(val);
      this.openAddOrUpload = true
      this.$nextTick(() => {
        this.$refs.addOrUpload.init(val, this.goodCates, this.ppOption,1)
      })
    },
    copygoods(val){
      console.log(val);
      this.openAddOrUpload = true
      this.$nextTick(() => {
        this.$refs.addOrUpload.init(val, this.goodCates, this.ppOption,2)
      })
    },
    whatIclick(type, data) {
      return {
        type,
        data
      }
    },
    deleteItem(val) {
      const idarr = []
      if (val === 1) {
        this.multipleSelection.forEach(e => {
          idarr.push(e.id)
        })
      } else {
        idarr.push(val.id)
      }
      const ids = idarr.join()
      this.$confirm('此操作将删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.httpPost('/products/delProducts', { ids: ids }).then(res=>{
            if (res) {
              this.$operateTip('已完成！', '已完成数据删除！', 'success')
              this.search()
            }
          })
        })
        .catch(() => {
          this.$operateTip('已取消！', '已取消数据删除！', 'info')
        })
    },
    handleCommand(e) {
      if (e.type === 'update') {
        this.addItem(e.data)
      } else if(e.type === 'copy'){
        this.copygoods(e.data)
      }else if (e.type === 'delete'){
        this.deleteItem(e.data)
      }else if(e.type==='look'){
        this.openLookInfo = true
        this.$nextTick(() => {
          this.$refs.lookInfo.init(e.data)
        })

      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.search()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.search()
    },
    // 列表多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>
<style lang="less"></style>
